package main

import (
	"encoding/json"
	"fmt"
	"github.com/google/martian/v3/log"
	"github.com/lzk97224/gomail"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

func main() {
	findStr := "currentStatus"
	processing := "PROCESSING"                     //处理中
	preparedForShipment := "PREPARED_FOR_SHIPMENT" //准备发货
	shipped := "SHIPPED"                           //已发货

	OrderStatus := make(map[string]string)

	index := 0
	for {
		res, err := http.Get("https://secure4.www.apple.com.cn/shop/order/guest/W933959617/e6720803e9777cd242ae1e5e5593a604f30b08bab3922dad2e0eec398061d18d1c34765131330e9a1d52a7a2fa90bb08c2e6f37151e86b662f2e735f7c0cea04?e=true")
		if err != nil {
			log.Infof("查询订单状态失败,err:%v", err)
			return
		}

		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			log.Infof("读取返回值失败,err:%v", err)
			return
		}

		bodyStr := string(body)

		begin := strings.Index(bodyStr, findStr) - 1

		end := strings.Index(bodyStr[begin:], "}")

		err = json.Unmarshal([]byte(fmt.Sprintf("{%s}", bodyStr[begin:begin+end])), &OrderStatus)
		if err != nil {
			log.Infof("反序列化数失败,err:%v", err)
			return
		}

		if strings.HasPrefix(OrderStatus[findStr], preparedForShipment) {
			log.Infof("准备发货了")
			SendMail("MAC订单状态变化", []string{"lizhikui@xiaoniangao.com"}, "当前状态：准备发货了")
			return
		}

		if strings.HasPrefix(OrderStatus[findStr], shipped) {
			log.Infof("已发货")
			SendMail("MAC订单状态变化", []string{"lizhikui@xiaoniangao.com"}, "当前状态：已发货")
			return
		}

		if OrderStatus[findStr] != processing {
			log.Infof("当前状态未知:%v", OrderStatus[findStr])
			SendMail("MAC订单状态变化", []string{"lizhikui@xiaoniangao.com"}, "未知状态："+OrderStatus[findStr])
			return
		}
		log.Infof("还在进行中")
		index++
		log.Infof("第%d次检查，没有变化", index)

		hour := time.Now().Hour()
		if 8 < hour && hour < 22 {
			log.Infof("白天：%v", hour)
			time.Sleep(time.Hour * 2)
		} else {
			log.Infof("晚上：%v", hour)
			time.Sleep(time.Hour * 4)
		}
	}

}

func SendMail(subject string, toMail []string, content string, fileNames ...string) error {

	m := gomail.NewMessage()
	m.SetHeader("From", "lizhikui@xiaoniangao.com")

	m.SetHeader("To", toMail...)

	m.SetHeader("Subject", subject)
	m.SetBody("text/html", "<b>"+content+"</b>")

	for _, fileName := range fileNames {
		m.Attach(fileName)
	}

	d := gomail.NewDialer("smtp.exmail.qq.com", 465, "lizhikui@xiaoniangao.com", "qcaaqmcZwmJdYA64")
	if err := d.DialAndSend(m); err != nil {
		log.Errorf("发送邮件失败，err:%v", err)
		return err
	}
	log.Infof("发送邮件成功，TO:%v", toMail)
	return nil
}
